package com.tiance.web.utils;

import com.tiance.constants.CommonConstants;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.text.MessageFormat;


/**
 *
 * @author 雷霆
 * @version 1.0.0
 * @date$ 2018/12/21
 *
 * Description：
 *
 * Modification History:
 *
 */
public class AccessUtil {

    private static Logger logger = LoggerFactory.getLogger(AccessUtil.class);

    private static final String[] HTTP_HEADER_IP_ADDRESS_ALL = {
            "x-forwarded-for", "Cdn-Src-Ip", "Proxy-Client-IP", "WL-Proxy-Client-IP" };

    /**
     * 获取Request IP地址
     * @param request HttpServletRequest
     * @return 返回IP地址，如果找不到则返回""。
     */
    public static String getClientIp(HttpServletRequest request) {
        return getIpAddress(request, HTTP_HEADER_IP_ADDRESS_ALL);
    }

    /**
     * 获得IP
     * @param request
     * @param ipHeaders
     * @return
     */
    private static String getIpAddress(HttpServletRequest request, String[] ipHeaders) {
        if (null == request || ipHeaders == null) {
            return null;
        }
        String ip = null;
        String header = null;
        for (String key : ipHeaders) {
            ip = request.getHeader(key);
            if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
                header = key;
                break;
            }
        }
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            header = "RemoteAddr";
        }
        logger
            .info(MessageFormat.format("获取IP：header为[{0}],IP为[{1}]", new Object[] { header, ip }));
        return ip == null ? "" : ip.split(",")[0];
    }






    /**
     * 判断是referer还是ip校验
     * 跳银行/跳收银台场景： 
     *      MAS标记：referrer校验 
     *      ACS过度校验规则：referrer没过验证IP 
     *      ACS终极校验规则：referrer没过验证IP 
     * 其他场景： 
     *      MAS标记： ip校验 
     *      ACS现在校验规则：IP没过验证referer 
     *      ACS终极校验规则：ip没过拒绝请求 
     * @param request
     * @return
     */
    public static Boolean validateIsUserSubmit(HttpServletRequest request) {
        return Boolean.FALSE;
    }

}
